{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4475c302",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from torchvision import transforms\n",
    "from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD\n",
    "from timm.data import create_transform\n",
    "from timm.data.transforms import _pil_interp\n",
    "from smt import SMT, build_transforms, build_transforms4display\n",
    "\n",
    "import os\n",
    "import numpy as np\n",
    "import torch.nn as nn\n",
    "from PIL import Image\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.image as image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4f871df8",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "build model\n",
    "'''\n",
    "img_size = 224\n",
    "\n",
    "# SMT\n",
    "model = SMT(\n",
    "        embed_dims=[64, 128, 256, 512], ca_num_heads=[4, 4, 4, -1], sa_num_heads=[-1, -1, 8, 16], mlp_ratios=[4, 4, 4, 2], \n",
    "        qkv_bias=True, depths=[3, 4, 18, 2], ca_attentions=[1, 1, 1, 0], head_conv=3, expand_ratio=2,).cuda()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00969042",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "build data transform\n",
    "'''\n",
    "eval_transforms = build_transforms(img_size, center_crop=False)\n",
    "display_transforms = build_transforms4display(img_size, center_crop=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27994844",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "load checkpoint\n",
    "'''\n",
    "ckpt_path = \"path/to/smt_small.pth\"\n",
    "ckpt = torch.load(ckpt_path)\n",
    "model.load_state_dict(ckpt['model'])\n",
    "model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d68f1927",
   "metadata": {},
   "outputs": [],
   "source": [
    "# visualize modulator \n",
    "upsampler = nn.Upsample(scale_factor=4, mode='bilinear')\n",
    "\n",
    "img_folder = \"./vis_images/\"\n",
    "img_paths = os.listdir(img_folder)\n",
    "for i, img_path in enumerate(img_paths):\n",
    "    img = Image.open(img_folder + img_path)\n",
    "    img_t = eval_transforms(img) \n",
    "    img_d = display_transforms(img)\n",
    "    out = model(img_t.unsqueeze(0).cuda())    \n",
    "\n",
    "    fig=plt.figure(figsize=(36, 8))\n",
    "    \n",
    "    # ori image\n",
    "    fig.add_subplot(1, 4, 1)       \n",
    "    img2d = img_d.permute(1, 2, 0).cpu().detach().contiguous().numpy()\n",
    "    x = plt.imshow(img_d.permute(1, 2, 0).cpu().detach().contiguous().numpy())     \n",
    "    plt.axis('off')\n",
    "    x.axes.get_xaxis().set_visible(False)\n",
    "    x.axes.get_yaxis().set_visible(False)    \n",
    "    plt.subplots_adjust(wspace=None, hspace=None)\n",
    "\n",
    "    # Modulator vis in stage 1\n",
    "    fig.add_subplot(1, 4, 2) \n",
    "    modulator = torch.abs((model.block1[-1].attn.modulator)).mean(1, keepdim=True)\n",
    "    print(modulator.size())\n",
    "    modulator = upsampler(modulator)\n",
    "    x = plt.imshow((modulator.squeeze(1)).permute(1, 2, 0).cpu().detach().contiguous().numpy())    \n",
    "    plt.axis('off')\n",
    "    x.axes.get_xaxis().set_visible(False)\n",
    "    x.axes.get_yaxis().set_visible(False)    \n",
    "    plt.subplots_adjust(wspace=0, hspace=0)  \n",
    "\n",
    "    # Modulator vis in stage 2\n",
    "    fig.add_subplot(1, 4, 3)    \n",
    "    modulator = torch.abs((model.block2[-1].attn.modulator)).mean(1, keepdim=True)\n",
    "    print(modulator.size())\n",
    "    modulator = upsampler(modulator)\n",
    "    x = plt.imshow((modulator.squeeze(1)).permute(1, 2, 0).cpu().detach().contiguous().numpy())    \n",
    "    plt.axis('off')\n",
    "    x.axes.get_xaxis().set_visible(False)\n",
    "    x.axes.get_yaxis().set_visible(False)    \n",
    "    plt.subplots_adjust(wspace=0, hspace=0)  \n",
    "\n",
    "    # Modulator vis in stage 3\n",
    "    fig.add_subplot(1, 4, 4)    \n",
    "    modulator = torch.abs((model.block3[-2].attn.modulator)).mean(1, keepdim=True)\n",
    "    print(modulator.size())\n",
    "    modulator = upsampler(modulator)\n",
    "    x = plt.imshow((modulator.squeeze(1)).permute(1, 2, 0).cpu().detach().contiguous().numpy())    \n",
    "    plt.axis('off')\n",
    "    x.axes.get_xaxis().set_visible(False)\n",
    "    x.axes.get_yaxis().set_visible(False)   \n",
    "\n",
    "    # plt.savefig('./figures/img_modulator_{}.png'.format(i),dpi=600)  "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
